//
//  MKMultiPhotosCollectionViewCell.swift
//  MKPhotoDetailDemo
//
//  Created by 劢克科技 on 2019/3/22.
//  Copyright © 2019 劢克科技. All rights reserved.
//

import UIKit

class MKMultiPhotosCollectionViewCell: UICollectionViewCell {
    
    var browseImage = UIImageView()
    
    lazy var scrollView = MKScrollView()
    
    var image: UIImageView? {
        didSet {
            setScrollView()
            setImageFrame()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - UI

extension MKMultiPhotosCollectionViewCell {
    
    fileprivate func setScrollView() {
        scrollView.maximumZoomScale = 3.0
        scrollView.minimumZoomScale = 1.0
        scrollView.delegate = self
        scrollView.frame = bounds
        scrollView.backgroundColor = .black
        addSubview(scrollView)
    }
    
    fileprivate func setImageFrame() {
        guard let image = image else {
            return
        }
        browseImage.image = image.image
        guard let imageSize = browseImage.image?.size else { return }
        let imageH = imageSize.height * UIScreen.main.bounds.width / imageSize.width
        var y = (UIScreen.main.bounds.height - imageH) / 2
        y = y < 0 ? 0 : y
        
        browseImage.frame = CGRect(x: 0, y: y, width: UIScreen.main.bounds.width, height: imageH)
        scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: imageH)
        scrollView.addSubview(browseImage)
    }
}

//MARK: - ScrollView 代理

extension MKMultiPhotosCollectionViewCell: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return browseImage
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        let x = scrollView.bounds.width > scrollView.contentSize.width ? (scrollView.bounds.width - scrollView.contentSize.width) / 2 : 0
        let y = scrollView.bounds.height > scrollView.contentSize.height ? (scrollView.bounds.height - scrollView.contentSize.height) / 2 : 0
        browseImage.center = CGPoint(x: scrollView.contentSize.width / 2 + x, y: scrollView.contentSize.height / 2 + y)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y <= 0 {
        }
    }
}
